package com.hancher.gamelife2.home;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.navigation.Navigation;
import androidx.sqlite.db.SimpleSQLiteQuery;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.hancher.common.androidutil.AsyncUtils;
import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.androidutil.MemoryUtil;
import com.hancher.common.androidutil.MmkvUtil;
import com.hancher.common.androidutil.StorageUtil;
import com.hancher.common.androidutil.ToastUtil;
import com.hancher.common.base.BaseMvpFragment;
import com.hancher.common.javautil.DateUtil;
import com.hancher.common.javautil.EmptyUtil;
import com.hancher.common.javautil.GsonUtil;
import com.hancher.common.javautil.StringUtil;
import com.hancher.common.rv.PageRecyclerViewManager;
import com.hancher.gamelife2.R;
import com.hancher.gamelife2.backup.BaiduNetApi;
import com.hancher.gamelife2.birthday.BirthdayPO;
import com.hancher.gamelife2.birthday.BirthdayUtil;
import com.hancher.gamelife2.databinding.FragmentHomeBinding;
import com.hancher.gamelife2.iciba.IcibaApi;
import com.hancher.gamelife2.login.BaiduLoginFragment;
import com.hancher.gamelife2.main.MainDatabase_Impl;
import com.hancher.gamelife2.position.BdMapManager;
import com.hancher.gamelife2.position.PositionPO;
import com.hancher.gamelife2.weather.CityCodeBean;
import com.hancher.gamelife2.weather.WeatherAllBean;
import com.hancher.gamelife2.weather.WeatherCityCodeUtil;
import com.hancher.gamelife2.weather.WeatherForestCnApi;
import com.hancher.gamelife2.weather.WeatherNow;
import com.hancher.gamelife2.weather.WeatherPO;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * 作者 : Hancher ytu_shaoweijie@163.com <br/>
 * 时间 : 2023/3/12 0012 22:49 <br/>
 * 描述 :
 */
public class HomeFragment extends BaseMvpFragment<FragmentHomeBinding, HomePresenter> {


    private PageRecyclerViewManager<HomeAdapter.HomeItem> prvmStatistic;
    private Disposable dTime;

    @SuppressLint("DefaultLocale")
    @Override
    protected void initView(Bundle savedInstanceState) {
        LogUtil.d("当前Fragment" + this);

    }

    @Override
    protected void initListener() {
    }

    @Override
    protected void initData() {
        initPerson();
        initChart();
        initFlow();
        initDay();
    }

    //region 4 每日一句
    private void initDay() {
        IcibaApi.dailySentence().subscribe(new Consumer<IcibaApi.DailySentence>() {
            @Override
            public void accept(IcibaApi.DailySentence dailySentence) throws Throwable {
                binding.tvDayTitle.setText(dailySentence.getNote());
                binding.tvDayContent.setText(dailySentence.getContent());
                Glide.with(binding.imgDay).load(dailySentence.getPicture()).into(binding.imgDay);
            }
        });
    }
    //endregion

    //region 1 流布局
    List<TagItem> tag = new ArrayList<>();
    TagAdapter<TagItem> tagAdapter = new TagAdapter<>(tag) {
        @Override
        public View getView(FlowLayout parent, int position, TagItem o) {
            View root = getLayoutInflater().inflate(R.layout.item_home_tag, binding.idFlowlayout, false);
            ((TextView) root.findViewById(R.id.tv_title)).setText(o.getTitle());
            ((TextView) root.findViewById(R.id.tv_msg)).setText(o.getMessage());
            return root;
        }
    };

    @Data
    @AllArgsConstructor
    public static class TagItem {
        private String title;
        private String message;
    }

    private void initFlow() {
        binding.idFlowlayout.setAdapter(tagAdapter);
        binding.idFlowlayout.setOnTagClickListener((view, position, parent) -> {
            if ("定位".equals(tag.get(position).getTitle())) {
                ToastUtil.show("开始定位");
                startPosition();
                return true;
            }
            return false;
        });
        initTime();
        initPosition();
        initStorage();
        initBirthday();
    }


    private void updateFlow() {
        tag.clear();

        tag.add(new TagItem("时间", DateUtil.getAllstr()));

        tag.add(memoryItem);
        tag.add(storageItem);

        if (EmptyUtil.isNotEmpty(weatherTag.getMessage())) {
            tag.add(weatherTag);
        } else {
            if (positionPO != null) {
                initWeather(positionPO.getLongitude(), positionPO.getLatitude(), positionPO.getProvince(), positionPO.getCity(), positionPO.getDistrict());
            }
        }

        if (EmptyUtil.isNotEmpty(positionTag.getMessage())) {
            tag.add(positionTag);
        }

        if (EmptyUtil.isNotEmpty(birthdayItem.getMessage())) {
            tag.add(birthdayItem);
        }
        if (!isResumed()) {
            LogUtil.v("放弃更新");
            return;
        }

        tagAdapter.notifyDataChanged();
    }

    //region 生日
    TagItem birthdayItem = new TagItem("生日", "");

    private void initBirthday() {
        AsyncUtils.run(emitter -> {
            String sql = " SELECT * FROM birthday WHERE deleteflag!=1 ";
            List<BirthdayPO> list = MainDatabase_Impl.getInstance().birthdayDao().getList(new SimpleSQLiteQuery(sql));
            List<BirthdayPO> lunarAndSolarBirthdayList = BirthdayUtil.birthday2LunarSolarBirthday(list, false);
            StringBuffer text = new StringBuffer();
            for (BirthdayPO item : lunarAndSolarBirthdayList) {
                if (item.getCountdownDay() == null || item.getCountdownDay() != 0) {
                    break;
                }
                if (EmptyUtil.isNotEmpty(text)) {
                    text.append("、");
                }
                text.append(item.getName());
            }
            emitter.onNext(text.toString());
        }, (Consumer<String>) data -> {
            if (EmptyUtil.isNotEmpty(data)) {
                birthdayItem.setMessage(data);
                updateFlow();
            }
        });
    }
    //endregion

    //region 存储 内存
    TagItem memoryItem = new TagItem("内存", "--");
    TagItem storageItem = new TagItem("存储", "--");

    private void initStorage() {
        AsyncUtils.run(emitter -> {
            List<BigDecimal> data = MemoryUtil.getMemory(MemoryUtil.Unit.GB, 2);
            String str = //StringUtil.getObjStr(data.get(0), "--") + "G/" + StringUtil.getObjStr(data.get(2), "--") + "G " +
                    StringUtil.getObjStr(data.get(1).divide(data.get(2), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)), "--") + "%";
            emitter.onNext(str);
            emitter.onComplete();
        }, (Consumer<String>) data -> {
            memoryItem.setMessage(data);
            updateFlow();
        });
        AsyncUtils.run(emitter -> {
            List<BigDecimal> data = StorageUtil.getStorage(MemoryUtil.Unit.GB, 2);
            String str = //StringUtil.getObjStr(data.get(0), "--") + "G/" + StringUtil.getObjStr(data.get(2), "--") + "G " +
                    StringUtil.getObjStr(data.get(1).divide(data.get(2), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)), "--") + "%";
            emitter.onNext(str);
            emitter.onComplete();
        }, (Consumer<String>) data -> {
            storageItem.setMessage(data);
            updateFlow();
        });
    }
    //endregion

    //region 天气
    TagItem weatherTag = new TagItem("天气", "");
    WeatherPO weatherPO = null;

    private void initWeather(Double longitude, Double latitude, String province, String city, String district) {
        AsyncUtils.run(emitter -> {
            try {
                List<WeatherPO> lastWeatherList = MainDatabase_Impl.getInstance().weatherDao().getList(new SimpleSQLiteQuery(" SELECT * FROM weather ORDER BY updateTime DESC LIMIT 1 "));
                if (EmptyUtil.isNotEmpty(lastWeatherList) && (System.currentTimeMillis() - lastWeatherList.get(0).getCreateTime() < DateUtil.ONE_HOUR)) {
                    LogUtil.d("获取最近天气成功");
                    emitter.onNext(lastWeatherList.get(0));
                    return;
                }
            } catch (Exception e) {
                LogUtil.e("err:", e);
            }
            //定位
            CityCodeBean cityCode = null;
            try {
                cityCode = WeatherCityCodeUtil.queryCityCode4(province, city,
                        StringUtil.getObjStr(BigDecimal.valueOf(longitude), ""),
                        StringUtil.getObjStr(BigDecimal.valueOf(latitude), ""));
            } catch (Exception e) {
                LogUtil.e("err:", e);
            }
            if (cityCode == null) {
                try {
                    List<WeatherPO> lastWeatherList = MainDatabase_Impl.getInstance().weatherDao().getList(new SimpleSQLiteQuery(" SELECT * FROM weather ORDER BY updateTime DESC LIMIT 1 "));
                    if (EmptyUtil.isNotEmpty(lastWeatherList)) {
                        CityCodeBean cityCodeBean = new CityCodeBean();
                        cityCodeBean.setCityCode(lastWeatherList.get(0).getCityCode());
                    }
                } catch (Exception e) {
                    LogUtil.e("err:", e);
                }
            }
            if (cityCode == null) {
                cityCode = new CityCodeBean("山东省", "烟台市", "芝罘区", "101120501");
            }
            //天气
            WeatherAllBean weather = WeatherForestCnApi.queryCity4Weather(cityCode.getCityCode());
            WeatherPO weatherPO = new WeatherPO();
            weatherPO.setWeatherHour(GsonUtil.obj2JsonStr(weather.getWeatherHours()));
            weatherPO.setWeatherDay(GsonUtil.obj2JsonStr(weather.getWeatherDays()));
            weatherPO.setWeatherNow(GsonUtil.obj2JsonStr(weather.getWeatherNow()));
            weatherPO.setWeatherNowUpdateTime(weather.getMeasureNowTime());
            weatherPO.setWeatherDayUpdateTime(weather.getMeasureDayTime());
            weatherPO.setWeatherHourUpdateTime(weather.getMeasureHourTime());
            MainDatabase_Impl.getInstance().weatherDao().insertItem(weatherPO);
            emitter.onNext(weatherPO);
        }, (Consumer<WeatherPO>) data -> {
            LogUtil.d("接收到天气：" + GsonUtil.obj2JsonStr(data));
            HomeFragment.this.weatherPO = data;
            WeatherNow weatherNow = GsonUtil.str2Obj2(weatherPO.getWeatherNow(), WeatherNow.class);
            HomeFragment.this.weatherTag.setMessage(weatherNow.getWeather() + " " + weatherNow.getTemp() + "℃");
            updateFlow();
        });
    }
    //endregion

    //region 定位
    private void initPosition() {

        //初始化
        LiveEventBus.get(BdMapManager.MAP_LOCATION_UPDATE, PositionPO.class)
                .observe(this, positionPO -> {
                    LogUtil.d("接收到定位：" + GsonUtil.obj2JsonStr(positionPO));
                    String address = positionPO.getCity() + positionPO.getDistrict() + positionPO.getPoiName();
                    HomeFragment.this.positionPO = positionPO;
                    HomeFragment.this.positionTag.setMessage(address);
                    updateFlow();
                });

        // 检查数据最后一条是否可以直接使用
        AsyncUtils.run(emitter -> {
            String stringBuffer = " SELECT * FROM position WHERE createTime BETWEEN " +
                    DateUtil.getFirstStampOfToday() +
                    " AND " +
                    DateUtil.getFirstStampOfToday(1) +
                    " ORDER BY createTime DESC LIMIT 1 ";
            List<PositionPO> lastPosition = MainDatabase_Impl.getInstance().positionDao().getList(new SimpleSQLiteQuery(stringBuffer));
            if (EmptyUtil.isNotEmpty(lastPosition)) {
                emitter.onNext(lastPosition.get(0));
            } else {
                PositionPO nullPosition = new PositionPO();
                nullPosition.setDeleteflag((byte) 1);
                emitter.onNext(nullPosition);
            }
        }, (Consumer<PositionPO>) positionPO -> {
            if (positionPO.getDeleteflag() != 1) {
                LogUtil.d("定位 显示今天最后一次定位");
                String address = positionPO.getCity() + positionPO.getDistrict() + positionPO.getPoiName();
                HomeFragment.this.positionPO = positionPO;
                HomeFragment.this.positionTag = new TagItem("定位", address);
                updateFlow();
            } else {
                startPosition();
            }
        });
    }

    PositionPO positionPO = null;

    TagItem positionTag = new TagItem("定位", "");

    private void startPosition() {
        LogUtil.d("开始检查权限");
        //非定位权限
        XXPermissions.with(getContext())
                .permission(Permission.WRITE_EXTERNAL_STORAGE)
                .permission(Permission.NEARBY_WIFI_DEVICES)
                .request((permissionsResult, allGranted) -> {
                    if (allGranted) {
                        //定位权限
                        XXPermissions.with(getContext())
                                .permission(Permission.ACCESS_COARSE_LOCATION)
                                .permission(Permission.ACCESS_FINE_LOCATION)
                                .permission(Permission.ACCESS_BACKGROUND_LOCATION)
                                .request((permissionsResult2, allGranted2) -> {
                                    if (allGranted2) {
                                        LogUtil.d("权限检查完毕，开始定位");
                                        BdMapManager.getInstance().start(getContext(), BdMapManager.START_TYPE.ADDRESS);
                                    } else {
                                        ToastUtil.show("权限未全部同意！");
                                    }
                                });
                    } else {
                        ToastUtil.show("权限未全部同意！");
                    }
                });
    }

    //endregion

    //region 时间
    BroadcastReceiver mTimeUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) return;
            String action = intent.getAction();
            if (action == null || action.isEmpty()) {
                return;
            }

            if (action.equals(Intent.ACTION_TIME_TICK)) {
                //系统每1分钟发送一次广播
                updateChartTime();
            } else if (action.equals(Intent.ACTION_TIME_CHANGED)) {
                //系统手动更改时间发送广播
                updateChartTime();
            }
        }
    };

    private void updateChartTime() {
        if (dTime != null && !dTime.isDisposed()) {
            dTime.dispose();
        }
        dTime = AsyncUtils.runCountdown(0L, 60L, 0L, 1000L, aLong -> {
            // TODO: 2023/12/13 更新
            if (binding == null || binding.pieChart == null) {
                return;
            }
            updateFlow();
//            binding.pieChart.setCenterText(DateUtil.getAllstr().replace(" ", "\n"));
//            binding.pieChart.invalidate();
        }, () -> {

        });
    }

    private void initTime() {
        if (getActivity() == null) {
            return;
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        getActivity().registerReceiver(mTimeUpdateReceiver, filter);

    }
    //endregion
    //endregion

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (getActivity() == null) {
            return;
        }
        getActivity().unregisterReceiver(mTimeUpdateReceiver);
    }

    //region 0人物信息
    private void initPerson() {
        String meBirthdayUuid = MmkvUtil.getString("BIRTHDAY_ME_UUID", "");
        AsyncUtils.run(emitter -> {
            if (EmptyUtil.isNotEmpty(meBirthdayUuid)) {
                List<BirthdayPO> birthdayPOs = MainDatabase_Impl.getInstance().birthdayDao()
                        .getList(new SimpleSQLiteQuery(" SELECT * FROM birthday WHERE uuid='" + meBirthdayUuid + "'"));
                if (EmptyUtil.isNotEmpty(birthdayPOs)) {
                    BirthdayPO item = birthdayPOs.get(0);
                    emitter.onNext(item);
                }
            }
        }, (Consumer<BirthdayPO>) item -> {
            Long birthdayStamp = DateUtil.ymdhms2stamp(item.getSolarY(), item.getSolarM(), item.getSolarD(), 1, 1, 1);
            binding.tvAge.setText(String.valueOf(DateUtil.getDiffYear(System.currentTimeMillis(), birthdayStamp)));
            listInfo(item);
        });

    }

    /**
     * 查询文件
     */
    public void listInfo(BirthdayPO birthdayPO) {
        BaiduNetApi.ListInfoDTO resquest = new BaiduNetApi.ListInfoDTO()
                .setAccess_token(MmkvUtil.getString(BaiduLoginFragment.BAIDUNET_ACCESS_TOKEN, ""))
                .setFsids(Arrays.asList(birthdayPO.getFsids()));
        BaiduNetApi.listInfo(resquest).subscribe(listInfoVO -> {
            if (EmptyUtil.isEmpty(listInfoVO.getList())) {
                return;
            }
            //将结果映射到diary数组中
            HashMap<String, String> fsidUrlMap = new HashMap<>();
            for (BaiduNetApi.ListInfoVO.Item item : listInfoVO.getList()) {
                if (item.getThumbs() == null) {
                    continue;
                }
                if (EmptyUtil.isNotEmpty(item.getThumbs().getUrl4())) {
                    fsidUrlMap.put(item.getFs_id(), item.getThumbs().getUrl4());
                } else if (EmptyUtil.isNotEmpty(item.getThumbs().getUrl3())) {
                    fsidUrlMap.put(item.getFs_id(), item.getThumbs().getUrl3());
                } else if (EmptyUtil.isNotEmpty(item.getThumbs().getUrl2())) {
                    fsidUrlMap.put(item.getFs_id(), item.getThumbs().getUrl2());
                } else if (EmptyUtil.isNotEmpty(item.getThumbs().getUrl1())) {
                    fsidUrlMap.put(item.getFs_id(), item.getThumbs().getUrl1());
                } else if (EmptyUtil.isNotEmpty(item.getThumbs().getIcon())) {
                    fsidUrlMap.put(item.getFs_id(), item.getThumbs().getIcon());
                }
            }
            //圆形头像
            Glide.with(binding.homeUser).load(fsidUrlMap.get(birthdayPO.getFsids()))
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .into(binding.homeUser);
        }, LogUtil::e);
    }
    //endregion

    //region 分析数据
    private void initStatistic() {
        prvmStatistic = new PageRecyclerViewManager<HomeAdapter.HomeItem>()
                .setContext(getContext())
                .setRecyclerView(binding.rvStatistic)
                .setAdapter(new HomeAdapter())
                .setCol(3)
                .setOnItemClickListener((baseQuickAdapter, view, i) -> {
                    try {
                        Navigation.findNavController(binding.pieChart).navigate(prvmStatistic.getRvList().get(i).getAction());
                    } catch (Exception e2) {
                        LogUtil.e("err:", e2);
                    }
                })
                .init();
        getStatisticData();
    }

    private void getStatisticData() {
        AsyncUtils.run(emitter -> {
            List<HomeAdapter.HomeItem> homeItems = new ArrayList<>();
            Integer allCount = MainDatabase_Impl.getInstance().matterDao().getAllCount();
            Integer finishedCount = MainDatabase_Impl.getInstance().matterDao().getFinishedCount();
            homeItems.add(HomeAdapter.HomeItem.builder()
                    .title("事项")
                    .msg(StringUtil.getObjStr(finishedCount, "0") + "/" + StringUtil.getObjStr(allCount, "0"))
                    .action(R.id.action_mainFragment_to_matterFragment)
                    .img(R.drawable.icon_matter)
                    .build());
            emitter.onNext(homeItems);
            emitter.onComplete();
        }, (Consumer<List<HomeAdapter.HomeItem>>) data -> {
            prvmStatistic.freshData(data);
        });
    }
    //endregion

    //region 2 图表

    private void initChart() {
        initPie(binding.pieChart);
        updateChart();
    }

    private void updateChart() {
        //状态数据初始化
        AsyncUtils.run(emitter -> {
            List<PieEntry> pes = new ArrayList<>();

            // 统计事务
            Integer allCount = MainDatabase_Impl.getInstance().matterDao().getAllCount();
            PieEntry pe1 = new PieEntry(allCount.floatValue(), "事项", R.id.action_mainFragment_to_matterFragment);
            pes.add(pe1);

            // 日记数据
            Integer diaryCount = MainDatabase_Impl.getInstance().diaryDao().count();
            PieEntry pe2 = new PieEntry(diaryCount.floatValue(), "日记", R.id.action_mainFragment_to_diaryListFragment);
            pes.add(pe2);

            // 生日数据
            Integer birthdayCount = MainDatabase_Impl.getInstance().birthdayDao().count();
            PieEntry pe3 = new PieEntry(birthdayCount.floatValue(), "生日", R.id.action_mainFragment_to_birthdayListFragment);
            pes.add(pe3);

            // 账户
            Integer accountCount = MainDatabase_Impl.getInstance().accountDao().count();
            PieEntry pe4 = new PieEntry(accountCount.floatValue(), "账户", R.id.action_mainFragment_to_accountListFragment);
            pes.add(pe4);

            // 打卡
            Integer colockinCount = MainDatabase_Impl.getInstance().colockInDao().countAll();
            PieEntry pe5 = new PieEntry(colockinCount.floatValue(), "打卡", R.id.action_mainFragment_to_colockInMainFragment);
            pes.add(pe5);

            PieData pd = new PieData(new PieDataSet(pes, ""));

            changePieDataStyle(pd);
            LogUtil.d("饼状图数据：" + GsonUtil.obj2JsonStr(pes));
            emitter.onNext(pd);

        }, (Consumer<PieData>) data -> {
            if (isResumed() && binding != null && binding.pieChart != null) {
                binding.pieChart.setData(data);
//                binding.pieChart.setCenterText(DateUtil.getAllstr().replace(" ", "\n"));
                binding.pieChart.invalidate();
            }
        });
    }

    private void initPie(PieChart pieChart) {
//        // TODO: 2023/12/14 获取宽高计算字体像素大小
//        float fontSize = pieChart.getWidth() / 10f;

        pieChart.setHighlightPerTapEnabled(true);//点击Item高亮是否可用
        pieChart.setDrawEntryLabels(true);//数据标签是否绘制
        pieChart.setEntryLabelColor(Color.WHITE);//数据标签颜色
        pieChart.setRotationEnabled(false);//设置pieChart图表是否可以手动旋转
        pieChart.getLegend().setEnabled(false);//图例关闭
        pieChart.getLegend().setOrientation(Legend.LegendOrientation.VERTICAL);//图例方向
        pieChart.getLegend().setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);//图例位置
        pieChart.getLegend().setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        pieChart.getDescription().setEnabled(false);//图表的描述关闭
//        pieChart.getDescription().setText("最近一周\n记录情况");
//        pieChart.getDescription().setTextSize(getResources().getDimension(com.hancher.common.R.dimen.sp_4));
//        pieChart.getDescription().setTextColor(getResources().getColor(com.hancher.common.R.color.fs_font_blue));
        pieChart.setCenterTextColor(Color.parseColor("#4169e1"));//中间标签颜色
        pieChart.setPadding(0, 0, 0, 0);
//        pieChart.setCenterTextSizePixels(fontSize);
//        pieChart.setEntryLabelTextSize(DensityUtil.px2dp(getContext(), fontSize));
        pieChart.setCenterTextSize(getResources().getDimension(com.hancher.common.R.dimen.sp_4));//中间文字
        pieChart.setEntryLabelTextSize(getResources().getDimension(com.hancher.common.R.dimen.sp_4));//数字标签文字
        pieChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                try {
                    ToastUtil.show("跳转" + ((PieEntry) e).getLabel());
                    Navigation.findNavController(binding.pieChart).navigate((Integer) e.getData());
                } catch (Exception e2) {
                    LogUtil.e("err:", e2);
                }
            }

            @Override
            public void onNothingSelected() {

            }
        });
    }

    private void changePieDataStyle(PieData pd) {
        PieDataSet pds = (PieDataSet) pd.getDataSet();
        pds.setColors(Color.parseColor("#4169e1"), Color.parseColor("#f5810b"),
                Color.parseColor("#f23b4c"), Color.parseColor("#228b22"),
                Color.parseColor("#ffd700"));
        pds.setUsingSliceColorAsValueLineColor(true);
        pds.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
//        // TODO: 2023/12/14 获取宽高计算字体像素大小
//        float fontSize = binding.pieChart.getWidth() / 50f;
        pds.setValueTextSize(getResources().getDimension(com.hancher.common.R.dimen.sp_4));//值字体大小
        pds.setValueTextColors(pds.getColors());
        pds.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return StringUtil.getObjStr(new BigDecimal(value), "0") + "条";
            }
        });
    }


    //endregion
}